package com.cskaoyan.search.service;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.dto.AllItemServiceResponse;
import com.cskaoyan.mall.dto.ItemDto;
import com.cskaoyan.search.converter.ProductConverter;
import com.cskaoyan.search.entity.ItemDocument;
import com.cskaoyan.search.remote.ProductApiClient;
import lombok.SneakyThrows;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author gatsby
 * @since 2022/11/02 15:53
 */
public class InitDataServiceImpl implements InitDataService {

    @Autowired
    ProductApiClient productApiClient;

    @Autowired
    ProductConverter productConverter;

    @Autowired
    RestHighLevelClient client;

    @SneakyThrows
    @Override
    public void initItems() {
        AllItemServiceResponse allProductItem = productApiClient.getAllProductItem();
        List<ItemDto> itemDtoList = allProductItem.getCallData();

        List<ItemDocument> itemDocuments = productConverter.items2Documnets(itemDtoList);

        //将每一个itemDocument对象转化为对应的json字符串，并存入es文档中
        BulkRequest bulkRequest = new BulkRequest();
        for (ItemDocument itemDocument : itemDocuments) {
            String itemJson = JSON.toJSONString(itemDocument);
            IndexRequest indexRequest = new IndexRequest("product");
            indexRequest.id(itemDocument.getId().toString())
                    .source(itemJson, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        //发起批量操作
        BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
    }
}
